package me.jessyan.mvparms.demo.mvp.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;

import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.nianlun.libserialport.UsbSerialPortController;
import com.platform.ai.control.R;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.mvparms.demo.di.component.DaggerUserComponent;
import me.jessyan.mvparms.demo.di.module.UserModule;
import me.jessyan.mvparms.demo.mvp.contract.UserContract;
import me.jessyan.mvparms.demo.mvp.model.entity.User;
import me.jessyan.mvparms.demo.mvp.presenter.UserPresenter;
import me.jessyan.mvparms.demo.mvp.ui.view.ZoomOutPageTransformer;
import me.jessyan.mvparms.demo.util.USBRsUtils;

import static com.platform.ai.control.R.id.mSwipeRefreshLayout;


@SuppressLint("ValidFragment")
public class CurtainFragment extends BaseFragment<UserPresenter> implements UserContract.View, SwipeRefreshLayout.OnRefreshListener, UsbSerialPortController.OnUsbSerialListener {
    @BindView(R.id.content)
    View mContent;


    @BindView(R.id.tv_curtain_name)
    TextView mCurtainName;

    @BindView(R.id.vp_introduce)
    ViewPager mIntroduce;

    private PagerAdapter mIntroduceAdapter;
    private List<View> mIntroduceList = new ArrayList<View>();

    public static CurtainFragment newInstance() {
        CurtainFragment fragment = new CurtainFragment();
        return fragment;
    }

    public CurtainFragment(){

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerUserComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .userModule(new UserModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_curtain, container, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {

        mIntroduceList.clear();
        addOffLineCurtainDevice();
        addOnlineCurtainDevice();
//        addOffLineCurtainDevice();
        initRecycleView();
        USBRsUtils.getInstance().init(getActivity(),this);
    }


    private void initRecycleView() {
        //加载ViewPager
        mIntroduce.setOffscreenPageLimit(mIntroduceList.size());
        mIntroduceAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return mIntroduceList.size();//页卡数
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;//官方推荐写法
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View v = mIntroduceList.get(position);
                ViewGroup parent = (ViewGroup) v.getParent();
                //Log.i("ViewPaperAdapter", parent.toString());
                if (parent != null) {
                    parent.removeAllViews();
                }
                container.addView(mIntroduceList.get(position));//添加页卡
                return mIntroduceList.get(position);
            }


            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mIntroduceList.get(position));//删除页卡
            }

        };

        //设置适配器
        mIntroduce.setAdapter(mIntroduceAdapter);
        mIntroduce.setPageMargin(20);
        mIntroduce.setOffscreenPageLimit(mIntroduceList.size());
        mIntroduce.setPageTransformer(true, new ZoomOutPageTransformer());//3D画廊模式

        //左右都有图
        mIntroduce.setCurrentItem(1);
        mCurtainName.setText("窗帘");
        //viewPager左右两边滑动无效的处理
        mContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return mIntroduce.dispatchTouchEvent(motionEvent);
            }
        });


        int count = mIntroduceList.size();
        mIntroduce.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        mCurtainName.setText("纱帘");
                        USBRsUtils.getInstance().sendUSBCurtainCommand(2);
                        break;
                    case 1:
                        mCurtainName.setText("窗帘");
                        break;
//                    case 2:
//                        mCurtainName.setText("卷帘");
//                        USBRsUtils.getInstance().sendUSBCurtainCommand(3);
//                        break;
                    default:

                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });



    }

    public void addOnlineCurtainDevice(){
        View investor = getActivity().getLayoutInflater().inflate(R.layout.view_curtain, null, false);
        ImageView iv_curtain = (ImageView) investor.findViewById(R.id.iv_curtain_device);
        iv_curtain.setImageResource(R.drawable.curtain_device_online);
        mIntroduceList.add(investor);
    }

    public void addOffLineCurtainDevice(){
        View investor = getActivity().getLayoutInflater().inflate(R.layout.view_curtain, null, false);
        ImageView iv_curtain = (ImageView) investor.findViewById(R.id.iv_curtain_device);
        iv_curtain.setImageResource(R.drawable.curtain_device_offline);
        mIntroduceList.add(investor);
    }
    /**
     * 此方法是让外部调用使fragment做一些操作的,比如说外部的activity想让fragment对象执行一些方法,
     * 建议在有多个需要让外界调用的方法时,统一传Message,通过what字段,来区分不同的方法,在setData
     * 方法中就可以switch做不同的操作,这样就可以用统一的入口方法做不同的事
     * <p>
     * 使用此方法时请注意调用时fragment的生命周期,如果调用此setData方法时onCreate还没执行
     * setData里却调用了presenter的方法时,是会报空的,因为dagger注入是在onCreated方法中执行的,然后才创建的presenter
     * 如果要做一些初始化操作,可以不必让外部调setData,在initData中初始化就可以了
     *
     * @param data
     */

    @Override
    public void setData(Object data) {

    }


    @Override
    public void showLoading() {

    }


    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        if (!message.isEmpty()) {

        }
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {

    }

    @Override
    public void killMyself() {

    }


    @Override
    public void setAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void loginReturn(User user) {

    }

    @Override
    public void logout() {

    }


    public void uploadResult(String string) {

    }

    @Override
    public void onRefresh() {

    }

    @OnClick(R.id.tv_on)
    public void ctrlOn(View v){
        showMessage("正在打开窗帘");
        USBRsUtils.getInstance().sendUSBCurtainCommand(1);
    }

    @OnClick(R.id.tv_pause)
    public void ctrlPause(View v){
        showMessage("正在暂停窗帘");
    }

    @OnClick(R.id.tv_off)
    public void ctrlOff(View v){
        showMessage("正在关闭窗帘");
        USBRsUtils.getInstance().sendUSBCurtainCommand(0);
    }

    @Override
    public void onUsbDeviceStateChange(int usbDeviceState, UsbDevice usbDevice) {

    }

    @Override
    public void onSerialOpenSuccess() {

    }

    @Override
    public void onSerialOpenException(Exception e) {

    }

    @Override
    public void onReceivedData(byte[] data) {

    }

    @Override
    public void onSendException(Exception e) {

    }
}
